package com.sky.service.user.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.mapper.admin.DishMapper;
import com.sky.mapper.admin.SetmealMapper;
import com.sky.mapper.user.ShoppingCartMapper;
import com.sky.pojo.ShoppingCart;
import com.sky.service.user.ShoppingCartService;
import com.sky.vo.DishVO;
import com.sky.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    //TODO 添加购物车
    @Override
    public void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        // TODO 根据前端传来的数据,我们造个购物车的实体类,然后拷贝属性
        ShoppingCart shoppingCart=new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        //前端传来的参数里面没有当前用户的ID,我们使用ThreadLocal获得当前登录人的ID
        shoppingCart.setUserId(BaseContext.getCurrentId());
        System.out.println(shoppingCart.getUserId());
        //为了复用我们写一个集合,但是只有一个购物车集合
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectByCondition(shoppingCart);
        if(shoppingCartList!=null&&shoppingCartList.size()==1){
            //不为空就说明当前购物车里面有这个商品,我们把这个商品的属性加一,需要重新去定义方法去修改数量
            //就一个购物车所以我们当前索引为0的就是当前购物车
                   shoppingCartMapper.addNumberById(shoppingCartList.get(0).getId());
        }
        else{
            //我们就去往购物车里面添加菜品或者套餐
            //先看是菜品还是套餐
            if(shoppingCart.getDishId()!=null){
                //是菜品就添加菜品,我们还需要添加额外的属性照片,name,数量,价格
                DishVO byId = dishMapper.getById(shoppingCart.getDishId());
                shoppingCart.setImage(byId.getImage());
                shoppingCart.setName(byId.getName());
                shoppingCart.setAmount(byId.getPrice());

            }
            else{
                //如果是套餐就添加套餐
                SetmealVO byId = setmealMapper.findById(shoppingCart.getSetmealId());
                shoppingCart.setImage(byId.getImage());
                shoppingCart.setName(byId.getName());
                shoppingCart.setAmount(byId.getPrice());
            }
            shoppingCart.setNumber(1);
            shoppingCartMapper.addShoppingCart(shoppingCart);
        }

    }

    /**
     * 查询购物车
     * @return
     */
    @Override
    public List<ShoppingCart> showShoppingCart() {
        //建一个购物车对象,至于为什么建,是因为我们需要组成查询条件
        ShoppingCart shoppingCart=new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        //调用上面定义好的
        return shoppingCartMapper.selectByCondition(shoppingCart);
    }

    @Override
    public void cleanShoppingCart() {
        //根据Id去删除
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());
    }
}
